<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>09.发布订阅模式理解实例</title>
  </head>
  <body>
    <button id="btn">click me!</button>

    <script>
      const btnDom = document.getElementById("btn");

      btnDom.onclick = () => {
        console.log("1111");
      };
      btnDom.onclick = () => {
        console.log("2222");
      };
      btnDom.addEventListener("click", function () {
        console.log("3333");
      });
      btnDom.addEventListener("click", function () {
        console.log("4444");
      });
    </script>
    <script>
      //事件集合
      const map = {};
      //收集事件
      function collect(eventName, fn) {
        if (!map[eventName]) {
          map[eventName] = [];
        }
        map[eventName].push(fn);
      }
      //触发事件
      function trigger(eventName) {
        map[eventName].forEach((itemFn) => {
          itemFn();
        });
      }
      collect("evn1", () => {
        console.log("name-evn1-11");
      });
      collect("evn1", () => {
        console.log("name-evn1-22");
      });
      collect("evn2", () => {
        console.log("name-evn2");
      });
    </script>
    <script>
      const Dev = {
        map: {},
        collect(eventName, fn) {
          if (!this.map[eventName]) {
            this.map[eventName] = [];
          }
          this.map[eventName].push(fn);
        },
        trigger(eventName) {
          this.map[eventName].forEach((itemFn, index) => {
            itemFn();
            console.log(`调用了${eventName}的方法${index + 1}`);
          });
        },
      };
      Dev.collect("evn1", () => {
        console.log("Dev-name-evn1-11");
      });
      Dev.collect("evn1", () => {
        console.log("Dev-name-evn1-22");
      });
      Dev.collect("evn2", () => {
        console.log("Dev-name-evn2");
      });
    </script>
  </body>
</html>
